package rsj.api.test;

import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import common.exec.RsjIllegalArgueException;
import common.util.BoxUtil;
import common.util.QueryRunnerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rsj.api.test.entity.DownloadOperLogParam;
import rsj.api.user.BaseLink;
import rsj.db.PostgresqlConn;
import rsj.service.test.ITestExportTemplateMethod;
import common.util.validator.ParameterConversionCheck;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * 导出对账文件
 *
 * @author yuanqinglong
 * @since 2021/3/17 11:39
 */
@RestController
public class DownloadOperLogController extends BaseLink {

    private static final Logger logger = LoggerFactory.getLogger(DownloadOperLogController.class);

    @Autowired
    private ITestExportTemplateMethod downloadOperLog;

    @Override
    @RequestMapping(value = "rsj_download_oper_log")
    public Box executeLink(Box box) throws SQLException {
        DownloadOperLogParam dataEntity = (DownloadOperLogParam) ParameterConversionCheck.parameterConversionCheckFastFail(box, DownloadOperLogParam.class);
        MapNode generatedFile = this.queryGeneratedFile(dataEntity.getLogId());
        if (this.fileHasBeenGenerated(generatedFile)) {
            return BoxUtil.successBox(box).putMapNode("data", generatedFile);
        }
        MapNode mapNode = downloadOperLog.performExport(dataEntity);
        this.saveGeneratedFile(mapNode, dataEntity.getLogId());
        return BoxUtil.successBox(box).putMapNode("data", mapNode);
    }


    /**
     * 查询是否已经导出并生成了文件  已经导出过直接返回文件id和名称
     *
     * @param logId 日志id
     * @return 文件id
     */
    private MapNode queryGeneratedFile(String logId) {
        String sql = "SELECT log_par_id AS file_id,log_par_name AS file_name FROM sys.sys_test_log WHERE log_id = '" + logId + "'";
        Connection connection = PostgresqlConn.getConnection();
        MapNode mapNode;
        try {
            mapNode = QueryRunnerFactory.getQueryRunner().queryLinkRow(connection, sql);
        }finally {
            Dbink.close(connection);
        }
        return mapNode;
    }


    /**
     * 保存生成的文件id和名称
     *
     * @param mapNode 文件id、名称
     * @param logId   日志id
     */
    private void saveGeneratedFile(MapNode mapNode, String logId) {
        String sql = "UPDATE sys.sys_test_log SET log_par_id = '" + mapNode.getValue("File_Id") + "'," +
                "log_par_name = '" + mapNode.getValue("File_Name") + "' WHERE log_id = '" + logId + "'";
        Connection connection = PostgresqlConn.getConnection();
        try {
            QueryRunnerFactory.getQueryRunner().update(connection, sql);
        } catch (SQLException e) {
            logger.error("saveGeneratedFile保存对账文件失败" + e);
            throw new RsjIllegalArgueException("文件导出失败");
        } finally {
            Dbink.close(connection);
        }
    }


    /**
     * 校验文件id和名称是否为空
     *
     * @param mapNode 文件信息
     * @return 校验结果 true 为空
     */
    private boolean fileHasBeenGenerated(MapNode mapNode) {
        String fileName = mapNode.getValue("File_Name");
        String fileId = mapNode.getValue("File_Id");
        return StringUtils.isNotBlank(fileName) && !Objects.equals("null", fileName) &&
                StringUtils.isNotBlank(fileId) && !Objects.equals("null", fileId);
    }
}
